import mysql.connector
from mysql.connector import Error


def get_address_ids_by_user_id(target_user_id):
    """根据 user_id 查询关联的 address_id 列表"""
    address_ids = []
    try:
        # 数据库连接配置（根据实际情况修改）
        connection = mysql.connector.connect(
            host="localhost",
            user="root",
            password="123456",
            database="esl"
        )

        if connection.is_connected():
            cursor = connection.cursor()

            # 参数化查询
            query = """
            SELECT address_id 
            FROM address 
            WHERE user_id = %s
            """
            cursor.execute(query, (target_user_id,))

            # 提取所有 address_id（过滤空值）
            address_ids = [row[0] for row in cursor.fetchall() if row[0]]

    except Error as e:
        print("数据库操作异常:", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
    return address_ids


# 使用示例
if __name__ == "__main__":
    user_id = "84ee6a1aaf274d0eba61df8e9737f276"  # 替换为实际 user_id

    result = get_address_ids_by_user_id(user_id)

    if result:
        print(f"用户 {user_id} 的地址ID列表：")
        for addr_id in result:
            print(f"- {addr_id}")
    else:
        print(f"用户 {user_id} 未登记地址信息")